package com.shengqin.listeners;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.shengqin.pojo.plan.result.ImportResultLineParam;
import com.shengqin.pojo.plan.result.ImportTestResultParam;
import com.shengqin.service.ITestResultService;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapperImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class TestResultLineListener implements ReadListener<ImportResultLineParam> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 240;
    /**
     * 缓存的数据
     */
    private List<ImportResultLineParam> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private ITestResultService testResultService;
    private Integer planId;

    public TestResultLineListener(ITestResultService bizTestResultService, Integer testPlanId) {
        this.testResultService = bizTestResultService;
        this.planId = testPlanId;
    }

    /**
     *
     */
    public TestResultLineListener() {

    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ImportResultLineParam data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        if(data.getSex().equalsIgnoreCase("男")){
            data.setSex("1");
        } else if (data.getSex().equalsIgnoreCase("女")){
            data.setSex("2");
        }
        if (data.getSex().equalsIgnoreCase("1")) {
            data.setRun1000(data.getRun800());
            data.setPullUp(data.getAbdominal());
        }
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.error("解析异常", exception);
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        List<ImportTestResultParam> importDataList = new ArrayList<>();
        cachedDataList.forEach(importData -> {
            ImportTestResultParam heightTestParam = getImportLineData(importData, "height","身高");
            ImportTestResultParam weightTestParam = getImportLineData(importData, "weight","体重");

            ImportTestResultParam hwParam = new ImportTestResultParam();
            BeanUtils.copyProperties(heightTestParam,hwParam);
            hwParam.setResult(heightTestParam.getResult() + " " + weightTestParam.getResult());
            hwParam.setPrjName("身高体重");
            importDataList.add(hwParam);

            importDataList.add(getImportLineData(importData, "run50","50米跑"));
            importDataList.add(getImportLineData(importData, "vital","肺活量"));
            importDataList.add(getImportLineData(importData, "sitAndReach","坐位体前屈"));
            importDataList.add(getImportLineData(importData, "standingJump","立定跳远"));
            if(importData.getSex().equalsIgnoreCase("男")){
                importData.setSex("1");
            } else if (importData.getSex().equalsIgnoreCase("女")){
                importData.setSex("2");
            }
            if (importData.getSex().equalsIgnoreCase("1")) {
                importDataList.add(getImportLineData(importData, "pullUp","引体向上"));
                importDataList.add(getImportLineData(importData, "run1000","1000米"));
            } else if (importData.getSex().equalsIgnoreCase("2")) {
                importDataList.add(getImportLineData(importData, "run800","800米"));
                importDataList.add(getImportLineData(importData, "abdominal","一分钟仰卧起坐"));
            }
        });
        Flowable.just(importDataList).subscribeOn(Schedulers.io()).subscribe(dataList -> {
            testResultService.importBatch(dataList, planId, "excel");
        });
        log.info("存储数据库成功！");
    }


    private ImportTestResultParam getImportLineData(ImportResultLineParam data, String prop,String name) {
        ImportTestResultParam importTestResultParam = new ImportTestResultParam();
        importTestResultParam.setName(data.getName());
        importTestResultParam.setSex(data.getSex());
        importTestResultParam.setStudyCode(data.getStudyCode());
        importTestResultParam.setPrjName(name);
        importTestResultParam.setResult(data.getHeight());

        BeanWrapperImpl beanWrapper = new BeanWrapperImpl(data);
        String value = (String) beanWrapper.getPropertyValue(prop);
        importTestResultParam.setResult(value);
        return importTestResultParam;
    }
}